package com.oa.android.activity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.RicTypeAdapter;
import com.oa.android.entry.Emil;
import com.oa.android.entry.Ric;
import com.oa.android.entry.RicType;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zouqh on 2016/6/19.
 */
public class AddRicActivity extends Activity implements View.OnClickListener {

    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.timeIcom1)
    ImageView timeIcom1;
    @InjectView(R.id.timeIcom2)
    ImageView timeIcom2;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    @InjectView(R.id.zhut)
    EditText zhut;
    @InjectView(R.id.startTime)
    EditText startTime;
    @InjectView(R.id.endTime)
    EditText endTime;
    @InjectView(R.id.tixTime)
    TextView tixTime;
    @InjectView(R.id.type)
    EditText type;
    @InjectView(R.id.sherePerson)
    TextView sherePerson;
    @InjectView(R.id.Content)
    EditText Content;

    ProgressDialog dialog;
    private List<RicType> ricList;
    private Dialog typeDialog;
    private Calendar c = null;
    private String idStr;
    private Ric ric;
    String personID = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_ric_activity);
        ric = (Ric) getIntent().getSerializableExtra("ric");
        ButterKnife.inject(this);
        if (null == ric) {
            titleText.setText("新增日程");
            ritghText.setText("提交");
            getId();
        } else {
            titleText.setText("修改日程");
            ritghText.setText("保存");
            zhut.setText(ric.getTITLE());
            startTime.setText(ric.getBEGINTIME());
            endTime.setText(ric.getENDTIME());
            type.setText(ric.getRCLX());
            sherePerson.setText(ric.getEMPNAMES());
            Content.setText(ric.getCONTENT());
            idStr = ric.getID();
        }

        ritghText.setVisibility(View.VISIBLE);
        close.setOnClickListener(this);
        ritghText.setOnClickListener(this);
        startTime.setOnClickListener(this);
        endTime.setOnClickListener(this);
        tixTime.setOnClickListener(this);
        timeIcom1.setOnClickListener(this);
        timeIcom2.setOnClickListener(this);
//        type.setOnClickListener(this);
        sherePerson.setOnClickListener(this);

        getRictype();
        type.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showtype();
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;
            case R.id.timeIcom1:
                onCreateDialog(startTime).show();
                break;
            case R.id.timeIcom2:
                onCreateDialog(endTime).show();
                break;
            case R.id.tixTime:
                onCreateDialog(tixTime).show();
                break;
            case R.id.type:

                break;
            case R.id.sherePerson:
                startActivityForResult(new Intent(this, PersonActivity.class), 1);
                break;

            case R.id.ritgh_text:
                String string1 = zhut.getText().toString();
                String string2 = startTime.getText().toString();
                String string3 = endTime.getText().toString();
                String string4 = tixTime.getText().toString();
                String string5 = type.getText().toString();
                String string6 = personID;
                String string7 = Content.getText().toString();
                if (!Util.NoNull(string1)) {
                    Toast.makeText(getApplicationContext(), "请输入主题！", Toast.LENGTH_SHORT).show();
                } else if (!Util.NoNull(string2)) {
                    Toast.makeText(getApplicationContext(), "请输入开始时间！", Toast.LENGTH_SHORT).show();
                } else if (!Util.NoNull(string3)) {
                    Toast.makeText(getApplicationContext(), "请输入结束时间！", Toast.LENGTH_SHORT).show();
                }
//                else if (!Util.NoNull(string4)) {
//                    Toast.makeText(getApplicationContext(), "请输入提醒时间！", Toast.LENGTH_SHORT).show();
//                }
                else if (!Util.NoNull(string5)) {
                    Toast.makeText(getApplicationContext(), "请选择事务类型！", Toast.LENGTH_SHORT).show();
                } else if (!Util.NoNull(string7)) {
                    Toast.makeText(getApplicationContext(), "请输入日程内容！", Toast.LENGTH_SHORT).show();
                } else {

                    if (null == ric) {
                        addRic(string1, string2, string3, string4, string5, string6, string7);
                    } else {
                        changeRic(string1, string2, string3, string4, string5, string6, string7);
                    }

                }

                break;
        }
    }

    /**
     * 选择类型
     */
    private void showtype() {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.sb_state_dailog,
                null);
        // 对话框
        typeDialog = new Dialog(this);
        typeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        typeDialog.show();

        typeDialog.setContentView(layout);
        ListView listView = (ListView) layout.findViewById(R.id.statesListView);
        listView.setAdapter(new RicTypeAdapter(AddRicActivity.this, ricList));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                type.setText(ricList.get(position).getSNAME());
                typeDialog.dismiss();
            }
        });

    }


    /**
     * 创建日期及时间选择对话框
     */
    int year;
    int month;
    int day;
    int hour;
    int minute;
    String strDate;
    String strtime;
    Dialog timeDialog = null;

    protected Dialog onCreateDialog(final TextView textView) {


        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.select_datatiem,
                null);
        // 对话框
        timeDialog = new Dialog(this);
        timeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        timeDialog.setContentView(layout);
        DatePicker datePicker = (DatePicker) layout.findViewById(R.id.picker);
        TimePicker timePicker = (TimePicker) layout.findViewById(R.id.time);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);

        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        day = c.get(Calendar.DAY_OF_MONTH);
        hour = c.get(Calendar.HOUR);
        minute = c.get(Calendar.MINUTE);
        strDate = year + "-" + month + "-" + day;
        strtime = hour + ":" + minute + ":00";
        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {

            @Override
            public void onDateChanged(DatePicker arg0, int years
                    , int months, int days) {
                year = years;
                month = months + 1;
                day = days;
//                Toast.makeText(AddRicActivity.this,"您选择的日期："+year+"年  "
//                        +month+"月  "+day+"日", Toast.LENGTH_SHORT).show();
                strDate = year + "-" + month + "-" + day;
            }
        });
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

            @Override
            public void onTimeChanged(TimePicker view
                    , int hourOfDay, int minutes) {
                hour = hourOfDay;
                minute = minutes;
                // 显示当前日期、时
                strDate = year + "-" + month + "-" + day;
                strtime = hour + ":" + minute + ":00";
            }
        });

        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(strDate + " " + strtime);
                timeDialog.dismiss();
            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                timeDialog.dismiss();
            }
        });
        return timeDialog;
    }

    /**
     * 创建日期及时间选择对话框
     */
    protected Dialog onDateDialog(final TextView textView) {
        Dialog dialog = null;

        c = Calendar.getInstance();
        dialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                        textView.setText(year + "/" + (month + 1) + "/" + dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
        );


        return dialog;
    }

    //新增日程
    private void addRic(String str1, String str2, String str3, String str4, String str5, String str6, String str7) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.ADD_RIC);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("TITLE", str1);
        params.addBodyParameter("BEGINTIME", str2);
        params.addBodyParameter("ENDTIME", str3);
//        params.addBodyParameter("TIMETIXING", str3);
        params.addBodyParameter("RCLX", str5);
        params.addBodyParameter("EMPIDS", str6);
        params.addBodyParameter("CONTENT", str7);
        params.addBodyParameter("ID", idStr);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);

                        boolean success = object.getBoolean("success");
//
                        if (success) {
                            dialog.dismiss();
                            Toast.makeText(x.app(), "提交成功！", Toast.LENGTH_LONG).show();
                            RicActivity.activity.setReash();
                            finish();
                        } else {
                            dialog.dismiss();
                            Toast.makeText(x.app(), "提交失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        dialog.dismiss();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "提交失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    //新增日程
    private void changeRic(String str1, String str2, String str3, String str4, String str5, String str6, String str7) {
        dialog = ProgressDialog.show(this, null, "修改中...", true, false);
        RequestParams params = new RequestParams(UConstants.CHANGE_RIC);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("TITLE", str1);
        params.addBodyParameter("BEGINTIME", str2);
        params.addBodyParameter("ENDTIME", str3);
//      params.addBodyParameter("TIMETIXING", str3);
        params.addBodyParameter("RCLX", str5);
        params.addBodyParameter("EMPIDS", str6);
        params.addBodyParameter("CONTENT", str7);
        params.addBodyParameter("ID", idStr);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);

                        boolean success = object.getBoolean("success");
//
                        if (success) {
                            dialog.dismiss();
                            Toast.makeText(x.app(), "修改成功！", Toast.LENGTH_LONG).show();
                            RicActivity.activity.setReash();
                            finish();
                        } else {
                            dialog.dismiss();
                            Toast.makeText(x.app(), "修改失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        dialog.dismiss();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "修改失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    //获取日程类型列表
    private void getRictype() {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_RIC_TYPE);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("SelId", "RCLX");
//        params.addBodyParameter("PAGE",  "");
//        params.addBodyParameter("ROWS","");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
//                        JSONObject object = new JSONObject(result);
//                        boolean success = object.getBoolean("success");
////                        String msg = object.getString("msg");
//                        if (success) {
                        Gson gson = new Gson();
                        Type lt = new TypeToken<List<RicType>>() {
                        }.getType();
                        ricList = gson.fromJson(result.toString(), lt);
//                            getJson(object.getString("rows").toString());


//                        } else {
////                            Toast.makeText(x.app(), "暂无邮件！", Toast.LENGTH_LONG).show();
//                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

//                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    String str = data.getStringExtra("person");
                    personID = data.getStringExtra("personID");
                    System.out.println("personID---" + personID);
                    sherePerson.setText(str);
                }
            }
        }

    }


    //获取ID
    public void getId() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
        RequestParams params = new RequestParams(UConstants.GET_ID);
//        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPRCGL");


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            idStr = msg;

                        } else {
                            Toast.makeText(x.app(), "获取新增失败！", Toast.LENGTH_LONG).show();

                        }
//
                    } catch (JSONException e) {

                        Toast.makeText(x.app(), "获取新增失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取新增失败！", Toast.LENGTH_LONG).show();

            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
